//
//  HWLNetworkTool.m
//  FloatClouds
//
//  Created by 黄威 on 16/8/30.
//  Copyright © 2016年 黄威. All rights reserved.
//

#import "HWLNetworkTool.h"
#import "AFNetworking.h"
@interface HWLNetworkTool()


@end

@implementation HWLNetworkTool

+(void)GET:(NSString *)url
   andBody:(id)body
 andHeader:(NSDictionary *)headers
andResponse:(HWLResponseStyle)responseStyle
andSuccessBlock:(successBlock)success
andFailureBlock:(failureBlock)failure
{
    
    // 1. 设置网络管理者
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2. 设置请求头
    
    if (headers) {
        
        for (NSString *key in headers.allKeys) {
            
            [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
            
        }
    }
    
    // 3. 设置返回数据的类型
    switch (responseStyle) {
        case HWLJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case HWLXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case HWLDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
            
        default:
            break;
    }
    
    // 4. 设置响应数据类型
    
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", @"text/xml", nil]];
    
    
    // 5. UTF-8转码
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    
    // 6. 使用AFN进行网络请求
    
    [manager GET:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            failure(error);
        }
        
    }];
}


+(void)POST:(NSString *)url andBody:(id)body andBodyStyle:(HWLRequestStyle)bodyStyle andHeader:(NSDictionary *)headers andResponse:(HWLResponseStyle)responseStyle andSuccessBlock:(successBlock)success andFailureBlock:(failureBlock)failure
{
    // 1. 设置网络管理者
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    
    // 2. 设置body的数据类型
    
    switch (bodyStyle) {
        case HWLBodyJSON:
            
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            
            break;
            
        case HWLBodyString:
            
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable * _Nullable error) {
                
                return parameters;
                
            }];
            
            break;
            
        default:
            break;
    }
    
    // 3. 设置请求头
    
    if (headers) {
        
        for (NSString *key in headers.allKeys) {
            
            [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
            
        }
    }
    
    // 3. 设置返回数据的类型
    switch (responseStyle) {
        case HWLJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case HWLXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case HWLDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
            
        default:
            break;
    }
    
    // 4. 设置响应数据类型
    
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    
    
    // 5. UTF-8转码
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    
    
    
    
    //离线缓存
    
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *cloudCaches = [documentPath stringByAppendingPathComponent:@"/default/com.hackemist.SDWebImageCache.default"];
    
    BOOL result = [fileManager createDirectoryAtPath:cloudCaches withIntermediateDirectories:YES attributes:nil error:nil];
    if (result == YES) {
        
    }else {
        
    }
    
    NSString *path = [NSString stringWithFormat:@"%ld.plist", (unsigned long)[body hash]];
    
    NSString *TextFilePath = [cloudCaches stringByAppendingPathComponent:path];

    
    
  //  NSLog(@"%@",NSHomeDirectory());
    
    
    // 6. 使用AFN进行网络请求
    
    
    
    [manager POST:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            success(responseObject);
            
            // 序列化（等同于将文件写入本地）
            BOOL result1 = [NSKeyedArchiver archiveRootObject:responseObject toFile:TextFilePath];
            if (result1) {
               // NSLog(@"写入成功");
            }else {
               // NSLog(@"写入失败");
            }
   
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            failure(error);
          
            NSDictionary *dic1 = [NSKeyedUnarchiver unarchiveObjectWithFile:TextFilePath];
            
            success(dic1);

           
        }
        
    }];
 
    
    
}





@end
